package com.zx.map.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.zx.map.dao.SystemBarDao;
import com.zx.map.dao.model.SystemBar;
import com.zx.map.dao.model.SystemBarExample;
import com.zx.map.service.SystemBarService;
import com.zx.map.service.domain.SystemBarDomain;
import com.zx.map.service.model.SystemBarModel;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.DesUtil;
import com.zx.platform.utils.ZipUtils;
import com.zx.scp.utils.MatrixToImageWriter;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-3-1 Time: 上午11:07 To
 * change this template use File | Settings | File Templates.
 */
@Component("systemBarService")
public class SystemBarServiceImpl implements SystemBarService {

	@Autowired
	private SystemBarDao dao;

	/**
	 * 得到所有数据列表
	 */
	public List getAllList() throws DataAccessException {

		List<SystemBar> list = dao.getListByExample(null);
		List<SystemBarModel> modelList = new ArrayList<SystemBarModel>();
		for (SystemBar o : list) {
			SystemBarModel temp = new SystemBarModel();
			BeanUtils.copyProperties(o, temp);
			modelList.add(temp);
		}
		return modelList;

	}

	/**
	 * 根据单Key查找Model
	 */
	public SystemBarModel getModelByKey(String key) throws DataAccessException {
		SystemBar o = dao.selectByPrimaryKey(key);
		SystemBarModel model = new SystemBarModel();
		BeanUtils.copyProperties(o, model);
		return model;
	}

	/**
	 * 根据Model查找列表
	 */
	public List getListByModel(SystemBarModel model) throws DataAccessException {
		SystemBarExample example = new SystemBarExample();
		com.zx.map.dao.model.SystemBarExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(model.getBatchNo())) {
			criteria.andBatchNoEqualTo(model.getBatchNo());
		}
		List<SystemBar> list = dao.getListByExample(example);
		List<SystemBarModel> modelList = new ArrayList<SystemBarModel>();
		for (SystemBar o : list) {
			SystemBarModel temp = new SystemBarModel();
			BeanUtils.copyProperties(o, temp);
			modelList.add(temp);
		}
		return modelList;
	}

	/**
	 * 新增
	 */
	public String add(SystemBarModel model) throws DataAccessException {
		SystemBar temp = new SystemBar();
		BeanUtils.copyProperties(model, temp);
		String key = dao.add(temp);
		return key;
	}

	/**
	 * 修改
	 */
	public String update(SystemBarModel model) throws DataAccessException {
		SystemBar temp = new SystemBar();
		BeanUtils.copyProperties(model, temp);
		dao.update(temp);
		return model.getBarId();
	}

	/**
	 * 删除
	 */
	public void delete(SystemBarModel model) throws DataAccessException {
		SystemBar temp = new SystemBar();
		BeanUtils.copyProperties(model, temp);
		dao.delete(temp);
	}

	/**
	 * 分页查询
	 * 
	 * @param pageSize
	 * @param pageNum
	 * @param domain
	 * @return
	 * @throws DataAccessException
	 */
	public Map getPageByDomain(int pageSize, int pageNum, SystemBarDomain domain)
			throws DataAccessException {

		Map<String, Object> map = new HashMap<String, Object>();
		SystemBarExample example = new SystemBarExample();
		com.zx.map.dao.model.SystemBarExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(domain.getBatchNo())) {
			criteria.andBatchNoEqualTo(domain.getBatchNo());
		}
		if(domain.getBegindate()!=null){
			criteria.andCreateDateGreaterThanOrEqualTo(domain.getBegindate());
		}

		Date enddate=null;		
		if(domain.getEnddate()!=null){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
			enddate=domain.getEnddate();
			String enddateStr=dateFormat.format(enddate);
			enddateStr=enddateStr+" 23:59:59";
			criteria.andCreateDateLessThanOrEqualTo(DateUtils.strToDate(enddateStr,"yyyy-MM-dd HH:mm:ss"));
		}
		//排序add by wenjw 2015.6.2
		example.setOrderByClause("create_Date desc");
		int pageBegin = (pageNum - 1) * pageSize;
		List<SystemBar> list = dao.getPageByExample(pageSize, pageBegin, example);
		List<SystemBarModel> menuModelList = new ArrayList<SystemBarModel>();
		for (SystemBar o : list) {
			SystemBarModel temp = new SystemBarModel();
			BeanUtils.copyProperties(o, temp);
			menuModelList.add(temp);
		}
		int count = dao.countByExample(example);
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}
	/**
	 * 根据batchNo group
	 * @return
	 * @throws DataAccessException
	 */
	public Map getPageByBatchNo(int pageSize, int pageNum, SystemBarDomain domain)
			throws DataAccessException {

		Map<String, Object> map = new HashMap<String, Object>();
		SystemBarExample example = new SystemBarExample();
		com.zx.map.dao.model.SystemBarExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(domain.getBatchNo())) {
			criteria.andBatchNoEqualTo(domain.getBatchNo());
		}
		if(domain.getBegindate()!=null){
			criteria.andCreateDateGreaterThanOrEqualTo(domain.getBegindate());
		}

		Date enddate=null;		
		if(domain.getEnddate()!=null){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
			enddate=domain.getEnddate();
			String enddateStr=dateFormat.format(enddate);
			enddateStr=enddateStr+" 23:59:59";
			criteria.andCreateDateLessThanOrEqualTo(DateUtils.strToDate(enddateStr,"yyyy-MM-dd HH:mm:ss"));
		}
		//排序add by wenjw 2015.6.2
		example.setOrderByClause("create_Date desc");
		int pageBegin = (pageNum - 1) * pageSize;
		List<SystemBar> list = dao.getPageByBatchNo(pageSize, pageBegin, example);
		List<SystemBarModel> menuModelList = new ArrayList<SystemBarModel>();
		for (SystemBar o : list) {
			SystemBarModel temp = new SystemBarModel();
			BeanUtils.copyProperties(o, temp);
			menuModelList.add(temp);
		}
		int count = 0;
		if(list.size()>0){
			count = dao.countByBatchNoExample(example);	
		}
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}

	@Override
	public String addByBatchCount(SystemBarModel model)
			throws DataAccessException {
		int batchCount = model.getBatchCount();

		SystemBarExample example = new SystemBarExample();
		com.zx.map.dao.model.SystemBarExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(model.getBatchNo())) {
			criteria.andBatchNoEqualTo(model.getBatchNo());
		}
		example.setOrderByClause("M_CODE desc");
		List<SystemBar> list = dao.getListByExample(example);
		int max =0;
		if(list!=null&&list.size()>0){
			SystemBar maxBar = list.get(0);
			String maxmCode = maxBar.getmCode();
			if(StringUtils.isNotEmpty(maxmCode)){
				String maxStr = maxmCode.substring(2, 8);
				max = Integer.valueOf(maxStr)+1;
			}
			
		}
		List pathList = new ArrayList();
		Date createDate = new Date();
		String batchNo = DateUtils.dateToString(createDate, "yyyyMMddHHmmss"); 
		for(int i=0;i<batchCount;i++){
			SystemBar newBar = new SystemBar();
			String newMCode = "A1"+String.format("%06d", max+i);
			newBar.setmCode(newMCode);
			newBar.setBarStatus("1");
			newBar.setBatchNo(batchNo);
			newBar.setCreateDate(createDate);
			//产生二维码及下载包
			try {
				String path = this.gengrBar(batchNo,newMCode);
				pathList.add(path);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dao.add(newBar);
		}
		String barPath = MatrixToImageWriter.realPath+File.separator+"systemBar"+File.separator+batchNo+File.separator;
		String zipPath = MatrixToImageWriter.realPath+File.separator+"systemBar"+File.separator+batchNo+".zip";
		try {
			List srcList = new ArrayList();
			File file = new File(barPath);
			srcList.add(file);
			//srcList再加2张模板文件
			File t1 = new File(MatrixToImageWriter.realPath+File.separator+"systemBar/t1.png");
			File t2 = new File(MatrixToImageWriter.realPath+File.separator+"systemBar/t2.png");
			if(t1.exists()){
				srcList.add(t1);
			}
			if(t2.exists()){
				srcList.add(t2);
			}
			ZipUtils.filesZip(zipPath,srcList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return zipPath;
	}
	public String gengrBar(String batchNo,String mCode) throws Exception{
		String text = PropertyUtil.getValue("mobile_base_url")+"/mobile/offline/index?offLineMerchantCode=&mCode="+mCode+"&appId=5202991"; // 二维码内容
        int width = 600; // 二维码图片宽度
        int height = 600; // 二维码图片高度
        String format = "png";// 二维码的图片格式
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");   // 内容所使用字符集编码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        // 生成二维码
        String path = MatrixToImageWriter.realPath+File.separator+"systemBar"+File.separator+batchNo+File.separator;
        //String filePath = path+DesUtil.encrypt(mCode, "systemBar")+".png";
        String filePath = path+mCode+".png";
        //File outputFile = new File("d:" + File.separator + "new.png");
        File pathFile = new File(path);
        File outputFile = new File(filePath);
        if(!pathFile.exists()){
        	pathFile.mkdirs();
        }
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		return path;
	} 
}
